package com.project.web.controller.home;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.project.entity.sys.Area;
import com.project.service.sys.CacheService;

@Controller
@RequestMapping("/home")
public class HomeController implements ApplicationListener<ContextRefreshedEvent>{
	
	@Autowired
	private CacheService cacheService;
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	
	@RequestMapping(value="home")
	public String home(Model model,HttpServletRequest request){
		model.addAttribute("provinceList", cacheService.getProvinceList());
		return "/home/home";
	}
	
	@RequestMapping(value="{module}/{page}")
    public String page(Model model, @PathVariable String module, @PathVariable String page){
        return module+"/"+page;
    }
	
	//根据省code获取市List
	@RequestMapping(value="getCityListByProvince")
	@ResponseBody
	public List<Area> getCityListByProvince(@RequestParam(required=false,value="provincecode") String provincecode){
		if(StringUtils.isEmpty(provincecode)){
			return null;
		}
		Map<String, Area> proCityMun = cacheService.getProCityMun();
		Area province = proCityMun.get(provincecode);
		List<Area> cityShowList = province.getAreaList();
		return cityShowList;
	}
	
	//根据省code获取市List
	@RequestMapping(value="getMunicipalityList")
	@ResponseBody
	public Map<String,Area> getMunicipalityList(String provincecode,String citycode){
		if(provincecode.isEmpty() || citycode.isEmpty()){
			return null;
		}
		return cacheService.getProCityMun().get(provincecode).getAityMap().get(citycode).getAityMap();
	}

	//根据市code获取区List
	@RequestMapping(value="getMunicipalityShowList")
	@ResponseBody
	public List<Area> getMunicipalityShowList(@RequestParam(required=false,value="provincecode") String provincecode,@RequestParam(required=false,value="citycode") String citycode){
		if(provincecode.isEmpty() || citycode.isEmpty()){
			return null;
		}
		return cacheService.getProCityMun().get(provincecode).getAityMap().get(citycode).getAreaList();
	}
	
	//项目启动时执行
	@Override
	public void onApplicationEvent(ContextRefreshedEvent arg0) {
//		cacheService.getProvinceList();
//		cacheService.getProCityMun();
	}
	
}
